package com.quanyan.user.service.impl;



import com.quanyan.comment.enums.TaskEnum;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.constants.MqConstants;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.mq.client.QcMsgClient;
import com.quanyan.mq.client.reqeust.MqRequestMsg;
import com.quanyan.redisCluster.utils.SerializeUtil;
import com.quanyan.statium.mq.UserRegisterMsg;
import com.quanyan.user.cache.MyRedisTemplate;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mapper.*;
import com.quanyan.user.model.db.*;
import com.quanyan.user.model.vo.response.RespUserTask;
import com.quanyan.user.mq.UserTaskMsg;
import com.quanyan.user.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 用户任务
 * Created by jian.zhou on 2016/6/30.
 */
@Service
public class UserTaskServiceImpl implements UserTaskService {

    private static final Logger logger = LoggerFactory.getLogger(UserTaskServiceImpl.class);

    @Autowired
    private TbTaskMapper tbTaskMapper;

    @Autowired
    private TbUserTaskMapper tbUserTaskMapper;

    @Autowired
    private UserTaskMapper userTaskMapper;

    @Autowired
    private TbUserTaskHistoryMapper tbUserTaskHistoryMapper;

    @Autowired
    private UserTaskHistoryMapper userTaskHistoryMapper;

    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @Autowired
    private UserQueryService userQueryService;

    @Autowired
    private UserInviteService userInviteService;

    @Resource(name = "qcMsgClient")
    private QcMsgClient qcMsgClient;

    @Autowired
    private UserExtService userExtService;

    @Autowired
    private TaskEggService taskEggService;

    /**
     * 获取新手任务
     * @param uid
     * @return
     */
    @Override
    public List<RespUserTask> queryUserNewHandTask(Integer uid){
        logger.info("获取用户新手任务 开始--------------------------》uid;{}",uid);
        List<RespUserTask> respUserTaskList  = new ArrayList<RespUserTask>();
        if(uid == null)
            return  respUserTaskList;

        TbUserTaskExample example = new TbUserTaskExample();
        TbUserTaskExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(uid);
        criteria.andTaskTypeEqualTo(UserConstants.NEW_HAND_TASK);
        int count = tbUserTaskMapper.countByExample(example);
        if(count < 1){
            logger.info("未找到用户新手任务信息");
            this.initUserTask(uid);
            logger.info("插入用户信息结束----");
        }

        TbUser user = userQueryService.getUser(uid);
        if(user != null && user.getMobile() != null){
            logger.info("开始查看绑定手机号任务是否完成！");
            TbUserTaskExample e = new TbUserTaskExample();
            TbUserTaskExample.Criteria c = e.createCriteria();
            c.andUidEqualTo(uid);
            c.andTaskIdEqualTo(TaskEnum.TASK_ENUM__MOBILE.getId());
            List<TbUserTask> userTasks = tbUserTaskMapper.selectByExample(e);
            if (userTasks != null && userTasks.size() > 0) {
                TbUserTask userTask = userTasks.get(0);
                if (userTask.getStatus().equals(UserConstants.TaskStatus.COMPLETE_ING)) {
                    this.whileNewTask(uid, TaskEnum.TASK_ENUM__MOBILE.getId());
                }
            }
        }

        Map<String,Object> map = new HashMap<String, Object>();
        map.put("uid",uid);
        map.put("taskType",UserConstants.NEW_HAND_TASK);
        respUserTaskList = userTaskMapper.queryUserTask(map);//用户新手任务
        logger.info("获取新手任务用户任务 结束 result--------------------------》");
        return respUserTaskList;
    }


    /**
     * 获取用户日常任务
     */
    @Override
    public List<RespUserTask> queryUserDayTask(Integer uid){
        logger.info("获取用户日常任务 开始--------------------------》uid;{}",uid);
        List<RespUserTask> respUserTaskList  = new ArrayList<RespUserTask>();
        if(uid == null)
            return  respUserTaskList;

        logger.info("开始从缓存中获取当日用户任务key:{}", UserConstants.getUserTaskRedisKey(uid));
        Map<byte[],byte[]> userTaskMap = myRedisTemplate.hgetAll(UserConstants.getUserTaskRedisKey(uid));
        if(userTaskMap == null || userTaskMap.size() < 1){
            logger.info("缓存中没有当日  日常任务，，，，，开始把系统任务分配给用户--------------》");
            this.setUserDayTask(uid,respUserTaskList);
            logger.info("系统任务分配给用户结束-----------------------------------》");
        }else {
            for(Map.Entry<byte[],byte[]> entry : userTaskMap.entrySet()){
                RespUserTask respUserTask = (RespUserTask)SerializeUtil.unserialize(entry.getValue());
                respUserTaskList.add(respUserTask);
            }
        }

        Comparator<RespUserTask> comparator = new Comparator<RespUserTask>() {
            @Override
            public int compare(RespUserTask o1, RespUserTask o2) {
                return o1.getTaskId().compareTo(o2.getTaskId());
            }
        };
        Collections.sort(respUserTaskList, comparator);


        logger.info("获取用户任务结束---------------------------》result:{}");
        return respUserTaskList;
    }

    /**
     * 设置当日用户任务
     * @param uid
     * @param respUserTaskList
     */
    public void setUserDayTask(Integer uid,List<RespUserTask> respUserTaskList){
        String uidTaskDayKey = UserConstants.getUserTaskRedisKey(uid);
        if(respUserTaskList == null)
            respUserTaskList = new ArrayList<>();
        Map<byte[],byte[]> map = myRedisTemplate.hgetAll(UserConstants.UC_SYS_TASK);//获取所有系统任务
        for (Map.Entry<byte[], byte[]> entry : map.entrySet()){
            TbTask tbTask = (TbTask)SerializeUtil.unserialize(entry.getValue());
            if(tbTask.getType() == UserConstants.DAY_TASK){
                RespUserTask respUserTask = new RespUserTask();
                respUserTask.setTaskId(tbTask.getId());
                respUserTask.setTaskName(tbTask.getTaskName());
                respUserTask.setRemark(tbTask.getRemark());
                if(tbTask.getReward() != null)
                    respUserTask.setReward(new BigDecimal(tbTask.getReward()));
                respUserTask.setTaskNum(tbTask.getTaskNum());
                respUserTask.setStatus(UserConstants.TaskStatus.COMPLETE_ING);//未完成
                respUserTask.setType(tbTask.getType());
                respUserTask.setCompletedNum(0);
                respUserTask.setTaskIcon(tbTask.getIcon());
                respUserTaskList.add(respUserTask);
                myRedisTemplate.hset(uidTaskDayKey,tbTask.getId().toString(),respUserTask);
            } // 只缓存日常任务
        }
        Map<byte[],byte[]> userTaskMap =myRedisTemplate.hgetAll(uidTaskDayKey);
        if(!this.isBidsVerify(uid)){//未认证
            logger.info("不是竞拍达人认证");
            String tid = String.valueOf(TaskEnum.TASK_ENUM_USER_CENTER_CREATE_JINGPAI.getId());
            myRedisTemplate.hdel(uidTaskDayKey,tid.getBytes());
            Iterator it = respUserTaskList.iterator();
            while(it.hasNext()){
                RespUserTask r = (RespUserTask)it.next();
                if(r.getTaskId() == TaskEnum.TASK_ENUM_USER_CENTER_CREATE_JINGPAI.getId())
                    it.remove(); //移除该对象

            }
            logger.info("删除竞拍任务！");
        }
        myRedisTemplate.setExpire(UserConstants.getUserTaskRedisKey(uid),1); //设置失效时间为一天
        logger.info("-----------------------------------------------》{}");

    }

    /**
     * false 未认证 true 已认证
     * @param uid
     * @return
     */
    public boolean isBidsVerify(Integer uid){
       TbUserExt tbUserExt =  userExtService.getTbUserExt(uid);
       if(tbUserExt != null){
           Byte isBidsVerify = tbUserExt.getIsBidsVerify();
           if(isBidsVerify == null)
               return false;
           return isBidsVerify.byteValue() == 0 ? false:true;
       }
        return false;
    }

    @Override
    public void initUserTask(Integer uid){
        if(uid == null)
            return;
        logger.info("开始初始化用户新手任务。。。。：uid:{}",uid);
        List<TbUserTask> tbUserTaskList = new ArrayList<TbUserTask>();
        Map<byte[],byte[]> map = myRedisTemplate.hgetAll(UserConstants.UC_SYS_TASK);
        if(map != null && map.size() > 0 ){
            for (Map.Entry<byte[], byte[]> entry : map.entrySet()){
                TbTask tbTask = (TbTask)SerializeUtil.unserialize(entry.getValue());
                if(tbTask.getType().byteValue() == UserConstants.NEW_HAND_TASK) {
                    TbUserTask tbUserTask = new TbUserTask();
                    tbUserTask.setUid(uid);
                    tbUserTask.setTaskId(tbTask.getId());
                    tbUserTask.setCompleteNum(0);//已完成次数 ：初始值 0
                    tbUserTask.setStatus(UserConstants.TaskStatus.COMPLETE_ING);//初始状态未完成
                    tbUserTask.setTaskType(tbTask.getType());
                    tbUserTask.setCreateTime(new Date());
                    tbUserTask.setUpdateTime(new Date());
                    tbUserTaskList.add(tbUserTask);
                }
            }
        }else {
            TbTaskExample tbTaskExample = new TbTaskExample();
            TbTaskExample.Criteria criteria = tbTaskExample.createCriteria();
            criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
            List<TbTask> lstTask = tbTaskMapper.selectByExample(tbTaskExample); // 查找状态正常的任务
            if (lstTask==null || lstTask.size()<1)
                return;
            logger.info("系统任务result:{}",lstTask.toString());
            tbUserTaskList = new ArrayList<TbUserTask>();
            for (TbTask tbTask : lstTask){ //只插入新手任务
                if(tbTask.getType() == UserConstants.NEW_HAND_TASK){
                    TbUserTask tbUserTask = new TbUserTask();
                    tbUserTask.setUid(uid);
                    tbUserTask.setTaskId(tbTask.getId());
                    tbUserTask.setCompleteNum(0);//已完成次数 ：初始值 0
                    tbUserTask.setStatus(UserConstants.TaskStatus.COMPLETE_ING);//初始状态未完成
                    tbUserTask.setTaskType(tbTask.getType());
                    tbUserTask.setCreateTime(new Date());
                    tbUserTask.setUpdateTime(new Date());
                    tbUserTaskList.add(tbUserTask);
                }
            }
        }

        userTaskMapper.batchInsert(tbUserTaskList);
    }


    /**
     * 丢弃。。。。。。。
     */
    @Override
    public void initDayUserTask(){
        logger.info("开始  定时 日常初始化用户任务。。。");
        TbUserTask tbUserTask = new TbUserTask();
        tbUserTask.setStatus(UserConstants.TaskStatus.COMPLETE_ING);
        tbUserTask.setCompleteNum(0);
        tbUserTask.setUpdateTime(new Date());

        TbUserTaskExample example = new TbUserTaskExample();
        example.createCriteria().andTaskTypeEqualTo(UserConstants.DAY_TASK);//日常任务
        tbUserTaskMapper.updateByExampleSelective(tbUserTask, example);

        logger.info("结束 定时 日常初始化用户任务。。。");


    }


    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void whileTask(Integer uid,Integer userTaskId,Integer taskId){
        logger.info("开始做任务---------------》用户：{}，用户任务：{}，系统任务：{}",uid,userTaskId,taskId);
        TbUserTask tbUserTask = tbUserTaskMapper.selectByPrimaryKey(userTaskId);//用户任务
        logger.info("用户当前任务详情:{}",tbUserTask.toString());
        TbTask tbTask = this.getTbTask(taskId);//系统任务
        if(tbUserTask.getStatus() > UserConstants.TaskStatus.COMPLETED){
            logger.info("任务已经完成");
            return;
        }// 已经完成任务

        tbUserTask.setCompleteNum(tbUserTask.getCompleteNum() + 1); // 当前完成次数
        if( tbUserTask.getCompleteNum().intValue() == tbTask.getTaskNum().intValue() )// 达到满足任务条件
            tbUserTask.setStatus(UserConstants.TaskStatus.COMPLETED);

        logger.info("开始更改用户任务状态与次数，param is {}:",tbUserTask.toString());
        tbUserTaskMapper.updateByPrimaryKeySelective(tbUserTask);//更改状态与完成次数次数

        TbUserTaskHistory tbUserTaskHistory = new TbUserTaskHistory();//增加用户做任务历史
        tbUserTaskHistory.setTaskId(taskId);
        tbUserTaskHistory.setUid(uid);
        tbUserTaskHistory.setIsDelete(Constants.IS_DELETE_FALSE);
        tbUserTaskHistory.setCreateTime(new Date());
        tbUserTaskHistory.setUpdateTime(new Date());
        tbUserTaskHistoryMapper.insert(tbUserTaskHistory);
        logger.info("结束增加用户做任务的历史");

    }

    @Override
    public void whileTask(Integer uid,Integer taskId){
        TbUser tbUser = userQueryService.getUser(uid);
        if(tbUser == null){
            logger.info("用户不存在-------");
            return;
        }

        TbTask tbTask = this.getTbTask(taskId);//系统任务
        if(tbTask == null){
            logger.info("系统任务不存在------------------------》");
            return ;
        }

        if(UserConstants.NEW_HAND_TASK == tbTask.getType())
            this.whileNewTask(uid,taskId);

        if(UserConstants.DAY_TASK == tbTask.getType())
            this.whileDayTask(uid,taskId);

    }


    @Override
    public void notifyWhenAddEgg(Integer uid, Integer taskId, Long addEgg){

        logger.info("notifyWhenAddEgg uid:{} taskId:{} addEgg:{}", uid, taskId, addEgg);

        if(uid == null || taskId == null || addEgg == null){
            return;
        }

        if(taskId.equals(TaskEnum.TASK_ENUM__T_EGG_SHELLS.getId()) && addEgg.compareTo(0L) > 0){
            taskEggService.addTaskFromOld(uid, addEgg.intValue());
        }

    }

    /**
     * 做新手任务
     * @param uid
     * @param taskId
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void whileNewTask(Integer uid,Integer taskId){
        logger.info("开始做新手任务---------------》uid{},taskId{}",uid,taskId);
        TbUserTaskExample tbUserTaskExample = new TbUserTaskExample();
        TbUserTaskExample.Criteria criteria = tbUserTaskExample.createCriteria();
        criteria.andUidEqualTo(uid);
        criteria.andTaskIdEqualTo(taskId);
        int count = tbUserTaskMapper.countByExample(tbUserTaskExample);
        if(count < 1){
            this.initUserTask(uid);
            logger.info("初始化新手任务完成");
        }

        List<TbUserTask> lst = tbUserTaskMapper.selectByExample(tbUserTaskExample);
        if (lst == null && lst.size() < 1)
            return;
        TbUserTask tbUserTask = lst.get(0);
        TbTask tbTask = (TbTask)myRedisTemplate.hget(UserConstants.UC_SYS_TASK,taskId.toString());//系统任务
        if(tbUserTask.getStatus().byteValue() > UserConstants.TaskStatus.COMPLETED){
            logger.info("新手任务已经完成！");
            return;
        }// 已经完成任务
        tbUserTask.setCompleteNum(tbUserTask.getCompleteNum() + 1); // 当前完成次数
        if( tbUserTask.getCompleteNum().intValue() == tbTask.getTaskNum().intValue() ){// 达到满足任务条件
            logger.info("更改该任务的状态:");
            tbUserTask.setStatus(UserConstants.TaskStatus.COMPLETED);
           // myRedisTemplate.set(UserConstants.USER_TASK_COMPLETE_KEY + uid.toString(),UserConstants.USER_TASK_COMPLETE_VALUE);
            tbUserTaskMapper.updateByPrimaryKeySelective(tbUserTask);//更改状态与完成次数次数
            logger.info("结束更改该任务的状态：{}", tbUserTask.getStatus());

            logger.info("开始增加用户做任务的历史");
            TbUserTaskHistory tbUserTaskHistory = new TbUserTaskHistory();//增加用户做任务历史
            tbUserTaskHistory.setTaskId(taskId);
            tbUserTaskHistory.setUid(uid);
            tbUserTaskHistory.setIsDelete(Constants.IS_DELETE_FALSE);
            tbUserTaskHistory.setCreateTime(new Date());
            tbUserTaskHistory.setUpdateTime(new Date());
            tbUserTaskHistory.setTaskType(tbTask.getType());
            tbUserTaskHistoryMapper.insert(tbUserTaskHistory);
            logger.info("结束增加用户做任务的历史");
        }
        logger.info("结束做任务------------------------------------------------------》");

        if(taskId.intValue() == TaskEnum.TASK_ENUM__MOBILE.getId()){
            logger.info("消息为绑定手机号消息 开始处理邀请的奖励");
            TbUser tbUser = userQueryService.getUser(uid);
            if(tbUser.getSourceChannel() == Constants.SourceChannel.APP){
                userInviteService.rewardUserRegister(uid);
            }
            logger.info("开始给户外发消息----------------》");
            UserRegisterMsg userRegisterMsg = new UserRegisterMsg();
            userRegisterMsg.setUid(tbUser.getId());
            userRegisterMsg.setCityId(tbUser.getAreaId());
            MqRequestMsg mqRequestMsg = new MqRequestMsg();
            mqRequestMsg.setTopic(MqConstants.StadiumUserRegisterConsumer.STADIUM_USER_REGISTER_TOPIC);
            mqRequestMsg.setTag(MqConstants.StadiumUserRegisterConsumer.STADIUM_USER_REGISTER_TAGS);
            mqRequestMsg.setBody(ObjectUtil.toByteArray(userRegisterMsg));
            qcMsgClient.asyncSend(mqRequestMsg);
            logger.info("结束给户外发消息----------------》");
        }

    }



    /**
     * 做日常任务
     * @param uid
     * @param taskId
     */
    public void whileDayTask(Integer uid ,Integer taskId) {
        logger.info("------------------------》用户：{}开始做日常任务：{}", uid, taskId);
        if(this.doTaskInRedis(uid,taskId))
            return ;
        logger.info("开始增加用户做任务的历史");
        TbUserTaskHistory tbUserTaskHistory = new TbUserTaskHistory();//增加用户做任务历史
        tbUserTaskHistory.setTaskId(taskId);
        tbUserTaskHistory.setUid(uid);
        tbUserTaskHistory.setIsDelete(Constants.IS_DELETE_FALSE);
        tbUserTaskHistory.setTaskType(UserConstants.DAY_TASK);
        tbUserTaskHistory.setCreateTime(new Date());
        tbUserTaskHistory.setUpdateTime(new Date());
        tbUserTaskHistoryMapper.insert(tbUserTaskHistory);
        logger.info("结束增加用户做任务的历史");

    }

    /**
     * 日常任务在redis中
     * @param uid
     * @param taskId
     */
    public boolean doTaskInRedis(Integer uid ,Integer taskId){
        TbTask tbTask = this.getTbTask(taskId);//系统任务
        if(tbTask == null){
            logger.info("该任务不存在，不处理-------》");
            return true;
        }
        Map<byte[],byte[]> userTaskMap =myRedisTemplate.hgetAll(UserConstants.getUserTaskRedisKey(uid));
        if(userTaskMap == null || userTaskMap.size() < 1){
            logger.info("缓存中没有当日任务，，，，，开始把系统任务分配给用户--------------》");
            this.setUserDayTask(uid,null);
        }
        logger.info("--->任务是：{}",tbTask.toString());

        RespUserTask respUserTask = (RespUserTask)myRedisTemplate.hget(UserConstants.getUserTaskRedisKey(uid), taskId.toString());//用户当日任务
        if(respUserTask == null){
            return true;
        }

        logger.info("获取用户当日任务----》{}",respUserTask.toString());
        if(respUserTask.getStatus() > UserConstants.TaskStatus.COMPLETE_ING ){
            logger.info("------------------------》任务已经完成！");
            return true;
        }
        int currentNum = respUserTask.getCompletedNum() + 1;
        respUserTask.setCompletedNum(currentNum);
        if(currentNum == tbTask.getTaskNum().intValue())
            respUserTask.setStatus(UserConstants.TaskStatus.COMPLETED);//变为领取状态
        myRedisTemplate.hset(UserConstants.getUserTaskRedisKey(uid),taskId.toString(),respUserTask);
        logger.info("处理日常任务结束------------------------------------------------------------------------>{}",myRedisTemplate.hget(UserConstants.getUserTaskRedisKey(uid),taskId.toString()).toString());
        return false;
    }


    public void doActivityTask(List<UserTaskMsg> userTaskMsgList){
        List<UserTaskMsg>  newHandLst = new ArrayList<UserTaskMsg>();
        Iterator<UserTaskMsg> iterator = userTaskMsgList.iterator();
        List<TbUserTaskHistory> tbUserTaskHistories = new ArrayList<TbUserTaskHistory>();
        while (iterator.hasNext()){
            UserTaskMsg u = iterator.next();
            TbTask tbTask = this.getTbTask(u.getTaskId());
            if(tbTask == null){
                logger.info("该任务不存在，不处理-------》");
                continue;
            }
            if(tbTask.getType() == UserConstants.NEW_HAND_TASK){//新手任务
                newHandLst.add(u);
            }else if(tbTask.getType() == UserConstants.DAY_TASK){
                logger.info("开始批处理做任务 in redis-------》{}：",userTaskMsgList.toString());
                if(this.doTaskInRedis(u.getUid(),u.getTaskId()))
                    continue;
                TbUserTaskHistory tbUserTaskHistory = new TbUserTaskHistory();//增加用户做任务历史
                tbUserTaskHistory.setTaskId(u.getTaskId());
                tbUserTaskHistory.setUid(u.getUid());
                tbUserTaskHistory.setIsDelete(Constants.IS_DELETE_FALSE);
                tbUserTaskHistory.setTaskType(UserConstants.DAY_TASK);
                tbUserTaskHistory.setCreateTime(new Date());
                tbUserTaskHistory.setUpdateTime(new Date());
                tbUserTaskHistories.add(tbUserTaskHistory);
            }
        }
        if(tbUserTaskHistories.size() > 0)
             userTaskHistoryMapper.batchInsert(tbUserTaskHistories);
        logger.info("结束批处理做日常任务 in redis-------》");

        if(newHandLst != null && newHandLst.size() > 0){
            logger.info("开始批处理新手任务");
            for(UserTaskMsg userTaskMsg:newHandLst){
                this.whileNewTask(userTaskMsg.getUid(),userTaskMsg.getTaskId());
            }
            logger.info("结束批处理新手任务");
        }

        logger.info("结束做任务------------------》");
    }


    /**
     * 是否完成新手任务 1 完成 0 未完成
     * @param uid
     * @return
     */
    public int isNewHandComplete(Integer uid){
        logger.info("开始查询用户：{}是否完成了新手任务------------------------》",uid);
        Map<byte[],byte[]> map = myRedisTemplate.hgetAll(UserConstants.UC_SYS_TASK);
        List<Integer> lst = new ArrayList<>();
        for (Map.Entry<byte[], byte[]> entry : map.entrySet()){
            TbTask tbTask = (TbTask)SerializeUtil.unserialize(entry.getValue());
            if(tbTask.getType().byteValue() == UserConstants.NEW_HAND_TASK)
                lst.add(tbTask.getId());
        }
        int newHandTaskCount = lst.size(); // 新手任务数量

        logger.info("系统新手任务数量result:{}",newHandTaskCount);
        TbUserTaskExample tbUserTaskExample = new TbUserTaskExample();
        TbUserTaskExample.Criteria criteria1 = tbUserTaskExample.createCriteria();
        criteria1.andUidEqualTo(uid);
        criteria1.andTaskIdIn(lst);
        criteria1.andTaskTypeEqualTo(UserConstants.NEW_HAND_TASK);
        criteria1.andStatusEqualTo(UserConstants.TaskStatus.RECEIVED);// 该用户完成的新手任务
        int completedNewHandTaskCount = tbUserTaskMapper.countByExample(tbUserTaskExample);
        logger.info("用户：{}已经完成的新手任务数量result:{}",uid,completedNewHandTaskCount);
        if(completedNewHandTaskCount == newHandTaskCount)
            return 1;
        else
            return 0;
    }


    @Override
    public void initSystemTask(){
        logger.info("开始删除老数据缓存---");
        myRedisTemplate.delteKey(UserConstants.UC_SYS_TASK);
        logger.info("开始缓存系统任务");
        TbTaskExample tbTaskExample = new TbTaskExample();
        tbTaskExample.setOrderByClause("id");
        TbTaskExample.Criteria criteria = tbTaskExample.createCriteria();
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbTask> lst= tbTaskMapper.selectByExample(tbTaskExample);
        if(lst == null || lst.size() < 1)
            return;

        for(TbTask tbTask :lst){
            myRedisTemplate.hset(UserConstants.UC_SYS_TASK,tbTask.getId().toString(),tbTask);
        }
        logger.info("结束缓存系统任务");
    }


    @Override
    public Boolean isNewTaskComplete(Integer uid, Integer taskId) {
        TbUserTaskExample example = new TbUserTaskExample();
        TbUserTaskExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(uid);
        criteria.andTaskIdEqualTo(taskId);
        List<TbUserTask> tbUserTaskList = tbUserTaskMapper.selectByExample(example);
        if(tbUserTaskList == null || tbUserTaskList.size() < 1)
            return true;

        TbUserTask tbUserTask = tbUserTaskList.get(0);
        return  UserConstants.TaskStatus.COMPLETED == tbUserTask.getStatus() ? true:false;
    }

    @Override
    public Boolean isDayTaskComplete(Integer uid, Integer taskId) {
        String key = UserConstants.getUserTaskRedisKey(uid);
        RespUserTask respUserTask = (RespUserTask)myRedisTemplate.hget(key,taskId.toString());
        if(respUserTask != null)
            return  UserConstants.TaskStatus.COMPLETED == respUserTask.getStatus() ? true:false;
        return true;
    }

    @Override
    public byte isTaoEgg(int uid){
        RespUserTask respUserTask = (RespUserTask)myRedisTemplate.hget(UserConstants.getUserTaskRedisKey(uid), String.valueOf(TaskEnum.TASK_ENUM__T_EGG_SHELLS.getId()));//用户当日任务
        if(respUserTask == null || respUserTask.getStatus() == UserConstants.TaskStatus.COMPLETE_ING)
            return 0; //未掏
        else
            return 1; //已掏
    }


    public TbTask getTbTask(Integer taskId){
        TbTask tbTask = (TbTask)myRedisTemplate.hget(UserConstants.UC_SYS_TASK,taskId.toString());//系统任务
        if (tbTask == null){
            tbTask = tbTaskMapper.selectByPrimaryKey(taskId);
        }
        if (tbTask.getIsDelete() == Constants.IS_DELETE_TRUE)
            return null;
        return tbTask;
    }

    @Override
    public void setUpTask(Integer taskId ,Integer type) {
        TbTask tbTask = new TbTask();
        tbTask.setId(taskId);
        if (Constants.IS_DELETE_FALSE == type.byteValue())
            tbTask.setIsDelete(Constants.IS_DELETE_FALSE);
        else
            tbTask.setIsDelete(Constants.IS_DELETE_TRUE);
        tbTaskMapper.updateByPrimaryKeySelective(tbTask);
        this.initSystemTask();
    }
}
